#include "sinks/filtering_sink.hpp"
#include <iostream>

FilteringSink::FilteringSink(std::shared_ptr<ISink> decorated_sink)
    : m_decoratedSink(std::move(decorated_sink)) {
    
    if (!m_decoratedSink) {
        std::cerr << "Warning: FilteringSink initialized with null decorated sink." << std::endl;
    }
}


void FilteringSink::addFilter(const std::string& pattern, const std::string& replacement) {
    try {
        m_filters.emplace_back(std::regex(pattern), replacement);
    } catch (const std::regex_error& e) {
        std::cerr << "Error: Invalid regex  pattern for log filter: " << pattern <<  " - " << std::endl;    
    }
}                                                             


void  FilteringSink::log(LogLevel level, const std::string& formatted_message) {
    if (!m_decoratedSink) {
        return; 
    }

    std::string filtered_message = formatted_message;
    for (const auto& filter : m_filters) {
        filtered_message = std::regex_replace(filtered_message, filter.first, filter.second);
    }
    // 将过滤后的消息传递给底层Sink
    m_decoratedSink->log(level, filtered_message);
} 

